import 'package:dailoz/dio/http_util.dart';
import 'package:dailoz/entity/user_entity.dart';
import 'package:dailoz/generated/l10n.dart';
import 'package:dailoz/response_json_entity.dart';
import 'package:dailoz/utils/showAlertDialog.dart';
import 'package:dailoz/utils/toast.dart';
import 'package:dailoz/view_model/user.dart';
import 'package:dailoz/views/splash.dart';
import 'package:flutter/cupertino.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';

class UserService {
  static Future<bool> getIsLogin() async {
    final prefs = await SharedPreferences.getInstance();
    bool isLogin = (prefs.getBool("isLogin") ?? false);
    return isLogin;
  }

  static Future<void> setIsLogin(bool isLogin) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setBool("isLogin", isLogin);
  }

  static Future<dynamic> signUp(User userInfo) async {
    var response = await HttpUtil().post("/user/userRegister", userInfo.toJson());
    return response;
  }

  static Future<bool> login(User userInfo) async {
    try {
      var response = await HttpUtil().post('/user/userLogin', userInfo.toJson());
      if (response != null) {
        ResponseJsonEntity responseJsonEntity = ResponseJsonEntity.fromJson(response);
        UserEntity userEntity = UserEntity.fromJson(responseJsonEntity.data);
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString("user-name", userEntity.userName);
        await prefs.setString("user-id", userEntity.id);
        await prefs.setInt("user-phone", userEntity.phoneNum);
        await prefs.setString("user-password", userEntity.password);
        await prefs.setString("user-token", userEntity.token);
        UserService.setIsLogin(true);
        showToast(responseJsonEntity.message);
        JPush().setAlias(userEntity.id);
        return true;
      }
      return false;
    } catch (e) {
      print("login error");
      return false;
    }
  }

  static void logout(BuildContext context) {
    ShowDialog.showAlertDialog(context, S.of(context).confirmLogout, () async {
      final prefs = await SharedPreferences.getInstance();
      final result = await prefs.clear();
      if (result) {
        // ignore: use_build_context_synchronously
        Navigator.of(context).pushNamedAndRemoveUntil(
          Splash.id,
          (Route<dynamic> route) => false,
        );
        JPush().deleteAlias();
      }
    });
  }
}
